package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.access.TimeInfoVo;
import com.ocom.webapi.feign.AccessClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class TimeInfoController {

    @Autowired
    private AccessClientService accessClientService;

    @PostMapping(WebApiServiceUrl.URL_AccessGroupPageGetTimeSlot)
    public Result accessGroupPageGetTimeSlot(@Valid  @RequestBody  TimeInfoVo timeInfoVo){
        log.info("TimeInfoVo1:"+timeInfoVo);
        try {
            if (timeInfoVo.getComId()==null){
                return ResultUtil.error(ResultEnum.Err_203);
            }
            timeInfoVo.setCompanyID(timeInfoVo.getComId());
            Result result=accessClientService.getAccessTimeSlots(timeInfoVo);
            if (result.getCode()==200){
                if (result.getData()==null){
                    Map<String,Object> map=new HashMap<>();
                    map.put("comId",timeInfoVo.getCompanyID());
                    map.put("areaNo",timeInfoVo.getAreaNo());
                    map.put("groupNo",timeInfoVo.getGroupNo());
                    map.put("zoneNo",timeInfoVo.getZoneNo());
                    map.put("timeSlots",new ArrayList<>());
                    return ResultUtil.success(map);
                }
                log.info("TimeInfoVo:result"+result);
                Map<String,Object> map= JSON.parseObject(JSON.toJSONString(result.getData()),Map.class);
                map.put("comId",timeInfoVo.getCompanyID());
                map.put("areaNo",timeInfoVo.getAreaNo());
                map.put("groupNo",timeInfoVo.getGroupNo());
                map.put("zoneNo",timeInfoVo.getZoneNo());
                return ResultUtil.success(map);
            }else {
                return result;
            }
        }catch (Exception e){
            log.info("获取开门时段:"+e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    //设置开门时段
    @PostMapping(WebApiServiceUrl.URL_AccessGroupPageSetTimeSlot)
    public Result AccessGroupPageSetTimeSlot(@RequestBody @Validated TimeInfoVo timeInfoVo){
        timeInfoVo.setCompanyID(timeInfoVo.getComId());
        return accessClientService.setAccessTimeSlots(timeInfoVo);
    }
}
